from datetime import datetime
from extensions import db


class _BaseModel(db.Model):
    """base model for flask-sqlalchemy"""

    __abstract__ = True

    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.TIMESTAMP, nullable=False, default=datetime.now)
    updated_at = db.Column(db.TIMESTAMP, nullable=False, default=datetime.now, onupdate=datetime.now)

    def save(self):
        """只能创建时保存"""
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """不允许物理删除"""
        if hasattr(self, 'deleted_at'):
            if self.deleted_at is None:
                self.deleted_at = datetime.now()
                db.session.commit()
        else:
            raise AttributeError(" '{}' object has no attribute 'delete' ".format(self.__class__.__name__))

    def __repr__(self):
        if hasattr(self, 'title'):
            return '<{}{}, {}>'.format(self.__class__.__name__, self.id, self.title)
        if hasattr(self, 'name'):
            return '<{}{}, {}>'.format(self.__class__.__name__, self.id, self.name)
        return '<{}{}>'.format(self.__class__.__name__, self.id)
